<template>
  <div class="d1-graphic-chart-question">
    <div class="slide-container" :class="{ 'slide-left': props.isAnalysis }">
      <!-- 答题区域 -->
      <div class="answer-view">
        <div class="question-container">
          <!-- 左侧材料区 -->
          <MaterialORnot />

          <askStatus v-if="examStore.currQuestion.showAnswer" />
          <div class="right-list">
            <!-- <askStatus :is-analysis="true" :is-correct="correct" /> -->
            <!-- 右侧题目区   :class="{ 'full-width': !props.leftContent }" -->
            <div class="right-content">
              <!-- 题干 -->
              <!-- 没有表格数据正常渲染 -->
              <div
                v-if="!tableOfTitle"
                class="question-title"
                v-html="mathHTMLToShow(examStore.currQuestion.title)"
              ></div>

              <!-- 表格渲染 -->
              <div class="question-title" v-else-if="tableOfTitle.length">
                <template v-for="item in tableOfTitle">
                  <span
                    v-if="item !== '<p>{【表格插入位置标识】}</p>'"
                    v-html="mathHTMLToShow(item)"
                  ></span>
                  <span v-else>
                    <el-table
                      ref="excelRef"
                      style="width: 100%"
                      :data="table?.[0]?.data?.slice(1)"
                      border
                    >
                      <el-table-column
                        :label="table?.[0]?.data?.[0]?.[it]"
                        :prop="it"
                        v-for="(it, ind) in table?.[0]?.filed"
                  sortable
                      />
                      <template #empty>
                        <div class="custom-loading">
                          <el-icon class="is-loading"><Loading /></el-icon>
                          正在加载中...
                        </div>
                      </template>
                    </el-table>
                  </span>
                </template>
              </div>

              <!-- 表格区域 -->
              <div class="table-wrapper">
                <table>
                  <thead>
                    <tr>
                      <th
                        v-for="(header, index) in examStore.currQuestion.answerList"
                        :key="index"
                      >
                        <span v-html="mathHTMLToShow(header.value)"></span>
                      </th>
                      <th></th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr
                      v-for="(row, rowIndex) in examStore.currQuestion.childList"
                      :key="rowIndex"
                    >
                      <td v-for="(radio, colIndex) in row.answerList" :key="colIndex">
                        <!-- 
                            'radio-correct': isAnalysis && colIndex == 0,
                            'radio-wrong': isAnalysis && colIndex == 1,
                            'radio-selected': isAnalysis && colIndex == 2, -->
                        <div
                          :key="radio.id"
                          class="option-item flex-center"
                          :class="{
                            'radio-ask':
                              !examStore.currQuestion.showAnswer && radio.is_check, //正常界面
                            'radio-correct':
                              examStore.currQuestion.showAnswer &&
                              examStore.currQuestion.answerList[colIndex].id ==
                                row.is_right,
                            'radio-wrong':
                              examStore.currQuestion.showAnswer &&
                              examStore.currQuestion.answerList[colIndex].id !==
                                row.is_right &&
                              radio.is_check,
                          }"
                          @click="handleAnswerSelect(row, radio, colIndex)"
                        >
                          <div class="radio-boxs">
                            <span class="radio-icon"></span>
                          </div>
                        </div>
                      </td>
                      <td class="option-text" v-html="mathHTMLToShow(row.title)"></td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 解析区域 -->
      <div class="analysis-view">
        <div class="analysis-content">
          <h3>答案解析</h3>
          <div class="answer-list">
            <div
              v-for="(answer, index) in columnAnswers"
              :key="index"
              class="answer-item"
            >
              <span>第{{ index + 1 }}列：{{ getAnswerText(index, answer) }}</span>
              <el-icon v-if="isCorrect(index)" color="#67C23A"><Select /></el-icon>
              <el-icon v-else color="#F56C6C"><Close /></el-icon>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import askStatus from "./askStatus.vue";
import { Loading } from "@element-plus/icons-vue";
import MaterialORnot from "./materialORnot.vue";
import { ref, watch } from "vue";
import { getQuestionExcel } from "@/service/exam";
import { Select, Close } from "@element-plus/icons-vue";
import { mathHTMLToShow, sortTable } from "@/utils/index";
import { useExam } from "@/stores/exam.js";
const examStore = useExam();

// 表格数据拆分
const table = ref([]);
const tableLoading = ref(true);
const tableOfTitle = computed(() => {
  if (!examStore.currQuestion.title.includes("<p>{【表格插入位置标识】}</p>")) {
    return "";
  } else {
    // getQuestionExcelFn()
    return examStore.currQuestion.title
      .split(/(<p>\{【表格插入位置标识】\}<\/p>)/)
      .filter((segment) => segment.trim() !== "");
  }
});

// 获取表格数据
const getQuestionExcelFn = async () => {
  const data = { qid: examStore.currQuestion.id, tid: 0 };
  const res = await getQuestionExcel(data);
  if (res.code === "000000") {
    tableLoading.value = false;
    table.value = [
      {
        name: "表格",
        data: sortTable(processTable(res.data)),
        filed: Object.keys(sortTable(res.data)[0] || {}).filter((it) =>
          it.includes("field")
        ),
      },
    ];
  }
};

// console.log(tableOfTitle.value, "tableOfTitletableOfTitle");
// if (examStore.currQuestion.title.includes("<p>{【表格插入位置标识】}</p>"))

const changehild = () => {
  let child = examStore.currQuestion.childList.map((it, ind) => {
    return {
      questionid3: it.id,
      answer:
        examStore.currQuestion.answerList?.[
          it.answerList.findIndex((i) => i.is_check == 1)
        ]?.id || "",
      is_right:
        examStore.currQuestion.answerList?.[
          it.answerList.findIndex((i) => i.is_check == 1)
        ]?.id == it.is_right
          ? 1
          : 0,
    };
  });

  examStore.currQuestion.child = child.filter((i) => i.answer);
  examStore.currQuestion.is_right = examStore.examInfo.section[
    examStore.currQuestion.sectionIndex
  ].question[examStore.currQuestion.index].is_right = child.every((i) => i.is_right == 1)
    ? 1
    : 0;
};

const handleAnswerSelect = (row, radio, colIndex) => {
  if (examStore.currQuestion.showAnswer) {
    return;
  }

  row.answerList.forEach((it) => (it.is_check = 0));
  radio.is_check = 1;
  changehild();
};

watch(
  () => examStore.currQuestion.childList,
  (val) => {
    val.forEach((child, index) => {
      if (
        examStore.currQuestion.answerList.findIndex((i) => i.id == child.is_check) !== -1
      ) {
        child.answerList[
          examStore.currQuestion.answerList.findIndex((i) => i.id == child.is_check)
        ].is_check = 1;
      }
    });

    changehild();
  },
  {
    deep: true,
    immediate: true,
  }
);

// 监听题目切换，做表格数据切换请求
watch(
  () => examStore.currQuestion?.id,
  () => {
    table.value = [];
    if (examStore.currQuestion.title.includes("<p>{【表格插入位置标识】}</p>")) {
      getQuestionExcelFn();
    }
  },
  {
    immediate: true,
  }
);

const props = defineProps({
  leftContent: {
    type: String,
    default: "",
  },
  questionTitle: {
    type: String,
    required: true,
  },
  headers: {
    type: Array,
    required: true,
  },
  options: {
    type: Array,
    required: true,
  },
  correctAnswers: {
    type: Array,
    required: true,
  },
  correct: {
    type: Boolean,
    default: true,
  },
  isAnalysis: {
    type: Boolean,
    default: true,
  },
});

const columnAnswers = ref(new Array(props.headers.length).fill(null));
const emit = defineEmits(["update:answers"]);

const handleRadioChange = (colIndex, rowIndex) => {};

const getAnswerText = (colIndex, answerIndex) => {
  if (answerIndex === null) return "未作答";
  return props.options[answerIndex]?.text || "";
};

const isCorrect = (index) => {
  return columnAnswers.value[index] === props.correctAnswers[index];
};
</script>

<style lang="scss" scoped>
.option-item {
  display: flex;
  align-items: center;
  // margin: 12px 0;
  padding: 5px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;

  &.radio-correct {
    .radio-boxs {
      border-color: #1e8fda;
    }

    .radio-icon {
      border-color: #1e8fda;
      background-color: #1e8fda;
    }
  }

  &.radio-wrong {
    .radio-boxs {
      border-color: #e52121;
    }

    .radio-icon {
      border-color: #e52121;
      background-color: #e52121;
    }
  }

  &.radio-ask {
    .radio-boxs {
      border-color: #126983;
    }

    .radio-icon {
      border-color: #126983;
      background-color: #126983;
    }
  }

  &.radio-selected {
    .radio-boxs {
      border-color: rgba(30, 143, 218, 0.4);
    }

    .radio-icon {
      border-color: rgba(30, 143, 218, 0.4);
      background-color: rgba(30, 143, 218, 0.4);
    }
  }
}

.radio-boxs {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: #fff;
  border: 1px solid #cccccc;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
  flex-shrink: 0;

  .radio-icon {
    width: 16px;
    display: block;
    height: 16px;
    // margin-right: 8px;
    border: 2px solid #ffff;
    border-radius: 50%;
    transition: all 0.3s;
  }
}

.right-list {
  display: flex;
  flex: 1;
}
.d1-graphic-chart-question {
  position: relative;
  overflow: hidden;

  .slide-container {
    display: flex;
    width: 200%;
    transition: transform 0.3s ease;

    &.slide-left {
      transform: translateX(-50%);
    }
  }

  .answer-view,
  .analysis-view {
    width: 50%;
    flex-shrink: 0;
  }

  .question-container {
    display: flex;

    // .left-content {
    // flex: 0 0 45%;

    // .content-box {
    //   border-right: 1px solid #dcdfe6;
    //   height: 100%;
    // }
    // }

    .right-content {
      // flex: 1;
      // flex: 0 0 55%;

      &.full-width {
        flex: 1;
      }

      .question-title {
        margin-bottom: 20px;
        line-height: 1.6;
      }
    }
  }

  .table-wrapper {
    width: 100%;
    overflow-x: auto;

    table {
      width: 100%;
      border-collapse: collapse;
      border: none;
      tr {
        height: 32px;
      }

      th,
      td {
        border: 1px solid #dcdfe6;
        padding: 12px;
        text-align: center;

        &.option-text {
          text-align: left;
          min-width: 200px;
        }
      }

      th {
        background-color: #f5f7fa;
        font-weight: 500;
      }

      .el-radio {
        margin-right: 0;
      }
    }
  }

  .analysis-view {
    padding: 20px;

    .analysis-content {
      background-color: #f8f9fa;
      padding: 20px;
      border-radius: 4px;

      h3 {
        margin-top: 0;
        margin-bottom: 16px;
      }

      .answer-list {
        .answer-item {
          display: flex;
          align-items: center;
          gap: 10px;
          margin-bottom: 12px;

          &:last-child {
            margin-bottom: 0;
          }
        }
      }
    }
  }
}

:deep(.el-radio__input) {
  width: 15px;
  height: 16px;
}
</style>
